import React, {useEffect} from 'react';
import {Button, Card, Checkbox, Empty, InputNumber, Space, Spin, Table, Typography} from 'antd';
import {DeleteOutlined, ShoppingCartOutlined} from '@ant-design/icons';
import {useCart} from '../hooks/useCart';
import {useCartStore} from '../store/cartStore';
import type {CartItemDto} from '../api/divide/cart/types.gen';

const { Title, Text } = Typography;

const Cart: React.FC = () => {
  const { 
    cartList, 
    isLoadingCart, 
    updateCartItem, 
    removeFromCart, 
    selectCartItem,
    clearCart 
  } = useCart();
  
  const { selectedItems, selectedTotalPrice, calculateSelectedTotal } = useCartStore();

  // 当购物车数据更新时重新计算
  useEffect(() => {
    calculateSelectedTotal();
  }, [selectedItems, calculateSelectedTotal]);

  // 处理商品选择
  const handleSelectItem = (item: CartItemDto, selected: boolean) => {
    selectCartItem({
      courseId: item.courseId!,
      selected
    });
  };

  // 处理数量变化
  const handleQuantityChange = (item: CartItemDto, quantity: number) => {
    if (quantity < 1) return;
    updateCartItem({
      courseId: item.courseId!,
      quantity
    });
  };

  // 处理删除商品
  const handleRemoveItem = (courseId: number) => {
    removeFromCart(courseId);
  };

  // 处理全选
  const handleSelectAll = (selected: boolean) => {
    cartList.forEach(item => {
      if (item.selected !== selected) {
        selectCartItem({
          courseId: item.courseId!,
          selected
        });
      }
    });
  };

  // 处理清空购物车
  const handleClearCart = () => {
    clearCart();
  };

  // 计算是否全选
  const isAllSelected = cartList.length > 0 && cartList.every(item => item.selected);

  // 表格列定义
  const columns = [
    {
      title: '选择',
      dataIndex: 'selected',
      key: 'selected',
      width: 80,
      render: (selected: boolean, record: CartItemDto) => (
        <Checkbox
          checked={selected}
          onChange={(e) => handleSelectItem(record, e.target.checked)}
        />
      )
    },
    {
      title: '课程名称',
      dataIndex: 'courseTitle',
      key: 'courseTitle',
      render: (text: any, record: CartItemDto) => (
          <Text strong>{record.courseTitle}</Text>
      )
    },
    {
      title: '课程图片',
      dataIndex: 'courseCover',
      key: 'courseCover',
      render: (text: any, record: CartItemDto) => (
          <img
              src={record.courseCover || '/placeholder-course.jpg'}
              alt={record.courseTitle}
              style={{ width: 80, height: 60, objectFit: 'cover', borderRadius: 4 }}
          />
      )
    },
    {
      title: '单价',
      dataIndex: 'coursePrice',
      key: 'coursePrice',
      width: 120,
      render: (price: number) => (
          <Text strong style={{ color: '#ff4d4f' }}>
            ¥{price?.toFixed(2) || '0.00'}
          </Text>
      )
    },

    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 120,
      render: (quantity: number, record: CartItemDto) => (
        <InputNumber
          min={1}
          value={quantity}
          onChange={(value) => handleQuantityChange(record, value || 1)}
          style={{ width: 80 }}
        />
      )
    },
    {
      title: '小计',
      dataIndex: 'subtotal',
      key: 'subtotal',
      width: 120,
      render: (text: any, record: CartItemDto) => (
        <Text strong style={{ color: '#ff4d4f' }}>
          ¥{((record.coursePrice || 0) * (record.quantity || 1)).toFixed(2)}
        </Text>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (text: any, record: CartItemDto) => (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleRemoveItem(record.courseId!)}
        >
          删除
        </Button>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ margin: 0 }}>
            <ShoppingCartOutlined /> 购物车
          </Title>
          {cartList.length > 0 && (
            <Button 
              danger 
              onClick={handleClearCart}
              loading={isLoadingCart}
            >
              清空购物车
            </Button>
          )}
        </div>

        <Spin spinning={isLoadingCart}>
          {cartList.length === 0 && !isLoadingCart ? (
            <Empty
              description="购物车是空的"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          ) : (
            <>
              <div style={{ minHeight: 400 }}>
                <Table
                  columns={columns}
                  dataSource={isLoadingCart ? [] : cartList}
                  rowKey="courseId"
                  pagination={false}
                  style={{ marginBottom: 24 }}
                  locale={{ emptyText: <Empty description="暂无数据" /> }}
                  loading={isLoadingCart}
                  scroll={{ x: 800 }}
                />
              </div>
              
              {cartList.length > 0 && (
                <Card style={{ marginTop: 24 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Space>
                      <Checkbox
                        checked={isAllSelected}
                        onChange={(e) => handleSelectAll(e.target.checked)}
                        disabled={isLoadingCart}
                      >
                        全选
                      </Checkbox>
                      <Text>
                        已选择 {selectedItems.length} 件商品
                      </Text>
                    </Space>
                    
                    <Space>
                      <Text>
                        总计: <Text strong style={{ color: '#ff4d4f', fontSize: 20 }}>
                          ¥{selectedTotalPrice.toFixed(2)}
                        </Text>
                      </Text>
                      <Button 
                        type="primary" 
                        size="large"
                        disabled={selectedItems.length === 0 || isLoadingCart}
                        loading={isLoadingCart}
                      >
                        去结算 ({selectedItems.length})
                      </Button>
                    </Space>
                  </div>
                </Card>
              )}
            </>
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default Cart;